# !/usr/bin/env python
# encoding: utf-8
# @File    : process_file_module.py
# @Time    : 2021/2/9
# @Author  : qiaowei
# @Version : 1.0
# @Email   : weiweiqiao@126.com
# @License : (C) Copyright 2013-2021
# @Brief   : main_window_module.MainWindow调用的文件操作类，根据UI界面的操作，发射信号槽进行不同的响应，
#            承担任务分解的角色


from PySide2.QtCore import QThread
from PySide2.QtCore import QObject
from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QFileDialog
# 信号槽
from PySide2.QtCore import Signal
from PySide2.QtCore import Slot
from process_package.process_data_module import TrackDataProcessing


class FileManager(QObject):
    def __init__(self):
        super(FileManager, self).__init__()

        self.__init_instance()
        self.__init_connections()

    def __del__(self):
        # print('delete')
        pass
        # if self.__split_data_thread.isRunning():
        #     self.__split_data_thread.quit()
        #     self.__split_data_thread.wait()

    def split_data_to_new_file(self):
        """
        打开对话框选择要拆分数据的文档，将文档名列表传给后端处理

        """
        # 获取打开的所有文件名列表
        files_in_list = QFileDialog.getOpenFileNames()[0]

        # 打开文件数不为0，将文件名列表传给后端处理
        if 0 != len(files_in_list):
            # 判断子线程状态，如果没有启动，则启动子线程
            # self.__start_sub_thread(self.__split_data_thread, self.__track_processing)
            self.__track_processing.moveToThread(self.__split_data_thread)
            self.__split_data_thread.finished.connect(self.__track_processing.deleteLater)
            self.si_file_name_with_path.connect(self.__track_processing.split_data_to_different_file)
            self.__split_data_thread.start()
            self.si_file_name_with_path.emit(files_in_list)

    @Slot()
    def __close_application(self):
        """
        退出程序

        """
        QApplication.closeAllWindows()

    def __init_instance(self):
        """
        初始化对象变量

        """
        self.__track_processing = TrackDataProcessing()
        self.__split_data_thread = QThread()

    def __init_connections(self):
        """
        初始化信号槽

        """
        # 信号槽新写法，推荐
        # 向槽函数传递打开文件名的列表
        self.si_close_application.connect(self.__close_application)

    def __start_sub_thread(self, thread: QThread, process: QObject):
        """
        启动将变量迁入子线程，启动子线程
        :param thread: 子线程
        :param process: 迁入子线程的变量

        """
        self.si_file_name_with_path.connect(self.__track_processing.split_data_to_different_file)
        if not thread.isRunning():
            process.moveToThread(thread)
            thread.finished.connect(process.deleteLater)
            self.si_file_name_with_path.connect(self.__track_processing.split_data_to_different_file)
            thread.start()

    # 信号声明
    # 打开的文件名及文件路径
    si_file_name_with_path = Signal(list)
    # 退出程序
    si_close_application = Signal()
